import React, { Component } from "react";
import TodoItem from "./todoItem";
class Todo extends Component {
  constructor(props) {
    super(props);
    this.state = {
      list: [],
      value: ""
    };
  }
  keyInput(e) {
    this.setState({
      value: e.target.value
    });
  }
  addTodo() {
    if (!this.state.value) return;
    this.setState({
      list: [...this.state.list, this.state.value],
      value: ""
    });
  }
  deleteTodo(index) {
    console.log("delete", index);
    const list = [...this.state.list];
    list.splice(index, 1);
    this.setState({ list });
  }
  keySub(e) {
    if (e.key === "Enter") this.addTodo();
  }
  render() {
    return (
      <div className="todo" onKeyPress={this.keySub.bind(this)}>
        <div className="todo-panel">
          <input
            value={this.state.value}
            type="text"
            onChange={this.keyInput.bind(this)}
          />
          <button onClick={this.addTodo.bind(this)}>添加</button>
        </div>
        <div className="todo-items">
          <ul>
            {this.state.list.map((item, index) => {
              return (
                <TodoItem
                  delete={this.deleteTodo.bind(this)}
                  content={item}
                  index={index}
                  key={index}
                />
              );
            })}
          </ul>
        </div>
      </div>
    );
  }
}

export default Todo;
